<template>
    <el-dialog :visible="visible" :center="true" width="460px" :before-close="handleClose">
        <span slot="title">{{ type == 'edit' ? '修改用户' : '添加用户' }}</span>
        <el-form :model="ruleForm" :rules="rules" :label-position="labelPosition" ref="ruleForm" label-width="100px"
            class="demo-ruleForm">
            <el-form-item label="用户名称" prop="username">
                <el-input v-model="ruleForm.username"></el-input>
            </el-form-item>
            <el-form-item label="用户密码" prop="password" v-if="type == 'add'">
                <el-input type="password" v-model="ruleForm.password"></el-input>
            </el-form-item>
            <el-form-item prop="email" label="邮箱">
                <el-input v-model="ruleForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input v-model.number="ruleForm.mobile"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
                <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script>
import { AddUsers, editUser } from '@/api/http';
export default {
    name: 'Dialog',
    props: { visible: Boolean, type: String, userInfo: Object },
    data() {
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            } else {
                if (this.ruleForm.checkPass !== '') {
                    this.$refs.ruleForm.validateField('checkPass');
                }
                callback();
            }
        };
        var checkTel = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('手机号不能为空'));
            }
            setTimeout(() => {
                if (value.length < 11) {
                    callback(new Error('手机号长度必须为11位'));
                } else {
                    callback();
                }
            }, 1000);
        };
        return {
            ruleForm: Object.assign({}, this.userInfo),
            labelPosition: 'right',
            rules: {
                username: [
                    { required: true, message: '请输入用户名称', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                password: [
                    { validator: validatePass, trigger: 'blur', required: true }
                ],
                email: [{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
                { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
                mobile: [
                    { validator: checkTel, trigger: 'blur', required: true }
                ],
            }
        }
    },
    watch: {
        visible: {
            immediate: true,
            handler(val) {
                val ? this.ruleForm = Object.assign(this.userInfo) : this.ruleForm = {}
            }
        }
    },
    methods: {
        // 关闭弹窗
        handleClose() {
            this.updateVisible(false)
        },
        // 提交
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.type == 'edit') {
                        this.EditUser()
                    } else {
                        this.addUser()
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // 添加用户
        async addUser() {
            const { data, meta } = await AddUsers(this.ruleForm)
            if (meta.status == 201) {
                this.$message.success(this.$t('message.updeteSuccess'))
                this.updateVisible(false)
                this.$emit('done')
            }
        },
        // 编辑用户
        async EditUser() {
            const { data, meta } = await editUser(this.userInfo.id, this.ruleForm)
            if (meta.status == 200) {
                this.$message.success(this.$t('message.updeteSuccess'))
                this.updateVisible(false)
                this.$emit('done')
            }
        },
        // 重置表格
        resetForm(formName) {
            this.ruleForm = {}
            this.$refs[formName].resetFields();
        },
        /* 更新visible */
        updateVisible(value) {
            this.$emit("update:visible", value);
        },
    },
}
</script>

<style lang="scss" scoped>
</style>